//
//  ServiceModel.m
//  somenew
//
//  Created by Valeriy Zinchenko on 20.12.12.
//  Copyright (c) 2012 Koby5. All rights reserved.
//

#import "ServiceModel.h"
#import "RssItem.h"
#import "APIDownload.h"
#import "XMLReader.h"

@implementation ServiceModel

@synthesize rssItems;
@synthesize delegate;

static ServiceModel * myModel = nil;

+ (ServiceModel *) sharedServiceModel
{
    if (!myModel)
    {
        myModel = [[ServiceModel alloc] init];
    }
    return myModel;
}

- (id) init
{
    self = [super init];
    rssItems = [[NSMutableArray alloc] init];
    return self;
}

- (void) dealloc
{
    [rssItems release];
    [delegate release];
    [super dealloc];
}

- (void) loadRssData
{
    [APIDownload downloadWithURL:@"http://bash.zennexgroup.com/service/ru/get.php?type=last" delegate:self];
}

- (void) APIDownload: (APIDownload *) request
{    
    @try
    {
        NSDictionary *xml = [[XMLReader dictionaryForXMLData:request.downloadData error:nil] retain];
        
        NSArray *quotes = [xml retrieveForPath:@"result.quotes.quote"];
        
        for (int i = 0; i < quotes.count; i++)
        {
            NSDictionary *quote = [quotes objectAtIndex:i];
            
            RssItem *item = [[RssItem alloc] init];
            
            item.itemId = [[quote retrieveForPath:@"id"] intValue];
            item.date = [quote retrieveForPath:@"date"];
            item.text = [quote retrieveForPath:@"text"];
            [rssItems addObject:item];
            
            [item release];
        }
        
        if([delegate retainCount] > 1)
        {
            if(!loadRssDataFinishSelector)
            {
                loadRssDataFinishSelector = @selector(loadRssDataFinish);
            }
            if([delegate respondsToSelector:loadRssDataFinishSelector])
            {
                [delegate performSelector:loadRssDataFinishSelector];
            }
        }
        
    }
    @catch (NSException *e)
    {
        
    }
}

@end
